package sporteam.web.server;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import sporteam.common.PMF;
import sporteam.web.client.AEuser;

import com.google.gson.Gson;

public class GetUserInfo extends HttpServlet {
	private static final Logger MyLog = Logger.getLogger(GetUserInfo.class
			.getName());
	private static final String SendLogURL = "http://sporteamtest.appspot.com/SendLog";
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("application/json");

		JSONObject responseJson = new JSONObject();
		AEuser ae_user = null, user = null;
		String request_type = null, facebook_ID = null, access_token = "";
		long last_updated_track = 0;
		Gson gson = new Gson();
		boolean pmClosed = false;
		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			// get essential variables from request
			request_type = request.getParameter("request_type");
			
			// check that request is valid
			if(request_type == null || request_type.equals(""))
		  	  throw new Exception();
			
			facebook_ID = request.getParameter("facebook_ID");

			// get user from appengine
			try {
				Object idInstance = pm.newObjectIdInstance(AEuser.class,
						facebook_ID);
				ae_user = (AEuser) pm.getObjectById(idInstance);
				pm.close();
				pmClosed = true;
			} catch (Exception e) {
				// in case no user found with this ID, create new user and store
				// in database
				try {
					access_token = request.getParameter("access_token");
				} catch (Exception err) {
					// in case no access_token was attached in request
					access_token = "";
				}
				pm.close();
				pmClosed = true;
				// handle new user registration
				MyLog.warning("handle new user registration, before reg. friends count: " /*+ ae_user.getSporteamFriends().size()*/);
				ae_user = UserLoadingUtils.HandleUserRegistration(facebook_ID,
						access_token);
				MyLog.warning("handle new user registration, after reg. friends count: " + ae_user.getSporteamFriends().size());
			}
			finally{
				if(!pmClosed)
					pm.close();
			}


			user = UserLoadingUtils.CreateBackupUser(ae_user);

			// handle queries types
			if (request_type.equals("get_tracks")) {
				// check for last updated track, if none exist, use default
				// value 0
				try {
					String str = (String) request
							.getParameter("last_updated_track");
					last_updated_track = Long.parseLong(str);
				} catch (Exception e) {
					// MyLog.warning("error in get_tracks:" + e.toString());
					last_updated_track = 0;
				}

				responseJson.put("tracks", gson.toJson(UserLoadingUtils
						.LoadTracks(user, last_updated_track)));
			}
			if (request_type.equals("get_all_tracks")) {
				responseJson.put("tracks", gson.toJson(ae_user.GetTracks()));
			} else if (request_type.equals("get_activities")) {
				responseJson.put("activities",
						gson.toJson(UserLoadingUtils.LoadActivities(user)));
			} else if (request_type.equals("get_all_activities")) {
				responseJson.put("activities",
						gson.toJson(ae_user.GetActivities()));
			} else if (request_type.equals("get_friends")) {
				responseJson.put("friends",
						gson.toJson(UserLoadingUtils.LoadFriends(user)));
			} else if (request_type.equals("get_user")) {
				responseJson.put("user",
						gson.toJson(UserLoadingUtils.LoadPartialUser(user)));
				responseJson.put("friends",
						gson.toJson(user.getSporteamFriends()));
			} else if (request_type.equals("get_whole_user")) {
				responseJson.put("user",
						gson.toJson(UserLoadingUtils.LoadWholeUser(user)));
			} else if (request_type.equals("get_user_for_sync")) {
				responseJson.put("user",
						gson.toJson(UserLoadingUtils.LoadPartialUser(user)));
				// check for last updated track, if none exist, use default
				// value 0
				try {
					String str = (String) request
							.getParameter("last_updated_track");
					last_updated_track = Long.parseLong(str);
				} catch (Exception e) {
					last_updated_track = 0;
				}

				responseJson.put("tracks", gson.toJson(UserLoadingUtils
						.LoadTracks(user, last_updated_track)));
				responseJson.put("activities",
						gson.toJson(UserLoadingUtils.LoadActivities(user)));
			}

		} catch (Exception e) {
			// MyLog.warning("failed on handling query " + request_type);
			
			if(request_type != null && request_type.length() > 0)
			  MyLog.warning(e.toString());
		}

		// write json to HTTP response
		response.getWriter().write(responseJson.toString());
		response.getWriter().flush();
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");

		// get JsonObject
		JSONObject json = JsonUtils.RetrieveJsonFromRequest(request);
		JSONObject responseJson = new JSONObject();
		Gson gson = new Gson();

		PersistenceManager pm = PMF.get().getPersistenceManager();
		AEuser ae_user = null;

		try {
			String request_type = (String) json.get("request_type");
			String facebook_ID = (String) json.get("facebook_ID");
			Object idInstance = pm.newObjectIdInstance(AEuser.class,
					facebook_ID);
			ae_user = (AEuser) pm.getObjectById(idInstance);

			if (request_type.equals("get_tracks")) {
				responseJson.put("tracks",
						gson.toJson(UserLoadingUtils.LoadTracks(ae_user)));
			}
			if (request_type.equals("get_all_tracks")) {
				responseJson.put("tracks", gson.toJson(ae_user.GetTracks()));
			} else if (request_type.equals("get_activities")) {
				responseJson.put("activities",
						gson.toJson(UserLoadingUtils.LoadActivities(ae_user)));
			} else if (request_type.equals("get_all_activities")) {
				responseJson.put("activities",
						gson.toJson(ae_user.GetActivities()));
			} else if (request_type.equals("get_friends")) {
				responseJson.put("friends",
						gson.toJson(UserLoadingUtils.LoadFriends(ae_user)));
			} else if (request_type.equals("get_user")) {
				responseJson.put("user",
						gson.toJson(UserLoadingUtils.LoadPartialUser(ae_user)));
			} else if (request_type.equals("get_user")) {
				responseJson.put("user",
						gson.toJson(UserLoadingUtils.LoadPartialUser(ae_user)));
			}
		} catch (Exception e) {
			MyLog.warning(e.toString());
		}

		// write json to HTTP response
		response.getWriter().write(responseJson.toString());
		response.getWriter().flush();
		pm.close();

	}
}